package com.demo.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

//session监听器：只能监听服务器创建或者销毁session
//session属性监听器：能监听session属性被add或者remove或者替换
public class OnlineListener implements HttpSessionListener, HttpSessionAttributeListener {

	@Override
	public void sessionCreated(HttpSessionEvent event) {
		HttpSession session = event.getSession();
		ServletContext application = session.getServletContext();
		application.setAttribute("nums", 1);
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent event) {//session的过期时间比较长
		
	}

	@Override
	public void attributeAdded(HttpSessionBindingEvent event) {//当前方法会监听session.setAttribute()
		HttpSession session = event.getSession();//会话级别
		ServletContext application = session.getServletContext();//全局级别：应用服务器start-stop期间
		
		if(application.getAttribute("nums")==null) {
			application.setAttribute("nums", 8978);//初始值
		}else {
			application.setAttribute("nums", ((int)application.getAttribute("nums"))+1);
		}
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent event) {//当前方法会监听session.removeAttribute()
		HttpSession session = event.getSession();
		ServletContext application = session.getServletContext();
		
		if(application.getAttribute("nums")==null) {
			application.setAttribute("nums", 8978);
		}else {
			application.setAttribute("nums", ((int)application.getAttribute("nums"))-1);
		}
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent event) {
		// TODO Auto-generated method stub
		
	}

}